<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件管理</title>
    <!-- 引入样式库 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        .file-table {
            white-space: nowrap;
        }
        .file-table th, .file-table td {
            vertical-align: middle;
        }
        .file-type-icon {
            font-size: 1.5rem;
            margin-right: 10px;
        }
        .file-image {
            color: #fd7e14;
        }
        .file-document {
            color: #0d6efd;
        }
        .file-archive {
            color: #6f42c1;
        }
        .file-code {
            color: #198754;
        }
        .file-excel {
            color: #198754;
        }
        .file-pdf {
            color: #dc3545;
        }
        .file-other {
            color: #6c757d;
        }
        .search-form {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .upload-area {
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            background-color: #f8f9fa;
            margin-bottom: 20px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .upload-area:hover {
            background-color: #e9ecef;
        }
        .upload-icon {
            font-size: 3rem;
            margin-bottom: 15px;
            color: #6c757d;
        }
        .upload-text {
            font-size: 1.1rem;
            color: #495057;
        }
        .file-preview {
            max-width: 100%;
            max-height: 300px;
            margin: 15px 0;
        }
        .preview-container {
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <h2 class="mb-4">文件管理</h2>
        
        <!-- 上传区域 -->
        <div class="upload-area" id="upload-area">
            <i class="bi bi-cloud-arrow-up upload-icon"></i>
            <div class="upload-text">拖放文件到此处或点击上传</div>
            <div class="mt-2"><small class="text-muted">支持的文件类型：图片、文档、压缩包等</small></div>
            <div class="preview-container mt-3 d-none" id="preview-container">
                <div id="file-preview"></div>
                <div id="file-info" class="mt-2"></div>
            </div>
            <form id="upload-form" enctype="multipart/form-data" class="d-none">
                <input type="file" id="file-input" class="d-none">
                <div class="mb-3 mt-3">
                    <label for="file-remark" class="form-label">备注</label>
                    <textarea class="form-control" id="file-remark" rows="2" placeholder="添加文件说明（可选）"></textarea>
                </div>
                <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                    <button type="button" class="btn btn-secondary me-md-2" id="cancel-upload">取消</button>
                    <button type="submit" class="btn btn-primary" id="submit-upload">上传文件</button>
                </div>
            </form>
        </div>
        
        <!-- 搜索表单 -->
        <div class="search-form">
            <form id="search-form">
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label for="file-name" class="form-label">文件名</label>
                        <input type="text" class="form-control" id="file-name" name="file_name" placeholder="请输入文件名">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label for="file-type" class="form-label">文件类型</label>
                        <select class="form-select" id="file-type" name="file_type">
                            <option value="">全部</option>
                            <option value="jpg">图片 (jpg, jpeg, png, gif)</option>
                            <option value="pdf">PDF文档</option>
                            <option value="doc">Office文档 (doc, docx, xls, xlsx, ppt, pptx)</option>
                            <option value="txt">文本文件 (txt, md)</option>
                            <option value="zip">压缩文件 (zip, rar, 7z)</option>
                        </select>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label for="uploader-name" class="form-label">上传者</label>
                        <input type="text" class="form-control" id="uploader-name" name="uploader_name" placeholder="请输入上传者">
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12 mb-3 d-flex justify-content-end">
                        <button type="submit" class="btn btn-primary me-2">
                            <i class="bi bi-search"></i> 搜索
                        </button>
                        <button type="reset" class="btn btn-secondary" id="reset-btn">
                            <i class="bi bi-x-circle"></i> 重置
                        </button>
                    </div>
                </div>
            </form>
        </div>
        
        <!-- 文件表格 -->
        <div class="table-responsive">
            <table class="table table-striped table-hover file-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>文件名</th>
                        <th>类型</th>
                        <th>大小</th>
                        <th>上传者</th>
                        <th>备注</th>
                        <th>上传时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="files-table-body">
                    <!-- 文件数据将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
        
        <!-- 分页控件 -->
        <div class="d-flex justify-content-between align-items-center mt-4 mb-4">
            <div>
                共 <span id="total-count">0</span> 个文件
            </div>
            <div>
                <nav aria-label="Page navigation">
                    <ul class="pagination" id="pagination">
                        <!-- 分页将通过JavaScript动态生成 -->
                    </ul>
                </nav>
            </div>
        </div>
    </div>
    
    <!-- 预览模态框 -->
    <div class="modal fade" id="preview-modal" tabindex="-1" aria-labelledby="preview-modal-label" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="preview-modal-label">文件预览</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <div id="modal-preview-content">
                        <!-- 预览内容将在这里显示 -->
                    </div>
                    <div class="mt-3" id="preview-file-info">
                        <!-- 文件信息将在这里显示 -->
                    </div>
                </div>
                <div class="modal-footer">
                    <a href="#" class="btn btn-primary" id="download-btn" download>
                        <i class="bi bi-download"></i> 下载
                    </a>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 引入jQuery和Bootstrap -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        let currentPage = 1;
        const pageSize = 10;
        let totalPages = 0;
        let previewModal = null;
        let selectedFile = null;
        
        // 初始化页面
        $(document).ready(function() {
            // 初始化模态框
            previewModal = new bootstrap.Modal(document.getElementById('preview-modal'));
            
            // 加载文件数据
            loadFiles();
            
            // 搜索表单提交
            $('#search-form').on('submit', function(e) {
                e.preventDefault();
                currentPage = 1;
                loadFiles();
            });
            
            // 重置按钮点击
            $('#reset-btn').click(function() {
                setTimeout(function() {
                    currentPage = 1;
                    loadFiles();
                }, 10);
            });
            
            // 上传区域点击
            $('#upload-area').click(function(e) {
                if (!$(e.target).closest('#upload-form').length || $(e.target).is('#upload-area')) {
                    $('#file-input').click();
                }
            });
            
            // 文件选择变化
            $('#file-input').change(function() {
                handleFileSelect(this.files[0]);
            });
            
            // 拖放文件
            const uploadArea = document.getElementById('upload-area');
            uploadArea.addEventListener('dragover', function(e) {
                e.preventDefault();
                e.stopPropagation();
                $(this).addClass('bg-light');
            });
            
            uploadArea.addEventListener('dragleave', function(e) {
                e.preventDefault();
                e.stopPropagation();
                $(this).removeClass('bg-light');
            });
            
            uploadArea.addEventListener('drop', function(e) {
                e.preventDefault();
                e.stopPropagation();
                $(this).removeClass('bg-light');
                
                if (e.dataTransfer.files.length) {
                    handleFileSelect(e.dataTransfer.files[0]);
                }
            });
            
            // 取消上传按钮
            $('#cancel-upload').click(function() {
                resetUploadForm();
            });
            
            // 提交上传
            $('#upload-form').submit(function(e) {
                e.preventDefault();
                uploadFile();
            });
        });
        
        // 处理文件选择
        function handleFileSelect(file) {
            if (!file) return;
            
            selectedFile = file;
            
            // 显示表单和预览
            $('#upload-form').removeClass('d-none');
            $('#preview-container').removeClass('d-none');
            
            // 显示文件信息
            const fileSize = formatFileSize(file.size);
            $('#file-info').html(`<strong>${file.name}</strong> (${fileSize})`);
            
            // 显示文件预览
            const fileExt = getFileExtension(file.name).toLowerCase();
            
            if (isImageFile(fileExt)) {
                // 预览图片
                const reader = new FileReader();
                reader.onload = function(e) {
                    $('#file-preview').html(`<img src="${e.target.result}" class="file-preview" alt="${file.name}">`);
                };
                reader.readAsDataURL(file);
            } else {
                // 显示文件图标
                const iconClass = getFileIconClass(fileExt);
                $('#file-preview').html(`<i class="bi ${iconClass} file-preview-icon" style="font-size: 5rem;"></i>`);
            }
        }
        
        // 上传文件
        function uploadFile() {
            if (!selectedFile) return;
            
            const formData = new FormData();
            formData.append('file', selectedFile);
            
            const remark = $('#file-remark').val();
            if (remark) {
                formData.append('remark', remark);
            }
            
            // 显示上传进度
            $('#submit-upload').prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 上传中...');
            
            $.ajax({
                url: '/admin/api/files',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                },
                success: function(response) {
                    // 上传成功
                    resetUploadForm();
                    alert('文件上传成功!');
                    loadFiles(); // 重新加载文件列表
                },
                error: function(error) {
                    console.error('文件上传失败', error);
                    alert('文件上传失败: ' + (error.responseJSON?.detail || '服务器错误'));
                    $('#submit-upload').prop('disabled', false).html('上传文件');
                }
            });
        }
        
        // 重置上传表单
        function resetUploadForm() {
            $('#file-input').val('');
            $('#file-remark').val('');
            $('#preview-container').addClass('d-none');
            $('#upload-form').addClass('d-none');
            $('#submit-upload').prop('disabled', false).html('上传文件');
            selectedFile = null;
        }
        
        // 加载文件列表
        function loadFiles() {
            // 获取筛选条件
            const formData = getFormData();
            
            // 添加分页参数
            formData.page = currentPage;
            formData.size = pageSize;
            
            // 发送请求
            $.ajax({
                url: '/admin/api/files',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                },
                data: formData,
                dataType: 'json',
                success: function(response) {
                    // 渲染文件表格
                    renderFilesTable(response.items);
                    
                    // 更新分页
                    renderPagination(response.total, response.page, response.pages);
                },
                error: function(error) {
                    console.error('获取文件列表失败', error);
                    alert('获取文件列表失败: ' + (error.responseJSON?.detail || '服务器错误'));
                }
            });
        }
        
        // 获取表单数据
        function getFormData() {
            const formData = {};
            const formArray = $('#search-form').serializeArray();
            
            // 将表单数据转换为对象
            $.each(formArray, function(i, field) {
                if (field.value) {
                    formData[field.name] = field.value;
                }
            });
            
            return formData;
        }
        
        // 渲染文件表格
        function renderFilesTable(files) {
            const tableBody = $('#files-table-body');
            tableBody.empty();
            
            if (files.length === 0) {
                tableBody.append('<tr><td colspan="8" class="text-center">暂无数据</td></tr>');
                return;
            }
            
            $.each(files, function(index, file) {
                const row = $('<tr></tr>');
                
                // 格式化时间
                const createdAt = new Date(file.created_at);
                const formattedTime = createdAt.toLocaleString();
                
                // 格式化文件大小
                const formattedSize = formatFileSize(file.file_size);
                
                // 获取文件图标
                const fileExt = getFileExtension(file.file_name);
                const iconClass = getFileIconClass(fileExt);
                
                // 添加单元格
                row.append(`<td>${file.id}</td>`);
                row.append(`
                    <td>
                        <i class="bi ${iconClass} file-type-icon"></i>
                        ${file.file_name}
                    </td>
                `);
                row.append(`<td>${file.file_type.toUpperCase()}</td>`);
                row.append(`<td>${formattedSize}</td>`);
                row.append(`<td>${file.uploader_name}</td>`);
                row.append(`<td>${file.remark || '-'}</td>`);
                row.append(`<td>${formattedTime}</td>`);
                row.append(`
                    <td>
                        <button type="button" class="btn btn-sm btn-info preview-file" data-id="${file.id}" data-url="${file.file_url}" data-name="${file.file_name}" data-type="${file.file_type}">
                            <i class="bi bi-eye"></i> 预览
                        </button>
                        <a href="/admin/api/files/${file.id}/download" class="btn btn-sm btn-success" target="_blank">
                            <i class="bi bi-download"></i> 下载
                        </a>
                        <button type="button" class="btn btn-sm btn-danger delete-file" data-id="${file.id}" data-name="${file.file_name}">
                            <i class="bi bi-trash"></i> 删除
                        </button>
                    </td>
                `);
                
                tableBody.append(row);
            });
            
            // 绑定预览按钮点击事件
            $('.preview-file').click(function() {
                const fileId = $(this).data('id');
                const fileUrl = $(this).data('url');
                const fileName = $(this).data('name');
                const fileType = $(this).data('type');
                previewFile(fileId, fileUrl, fileName, fileType);
            });
            
            // 绑定删除按钮点击事件
            $('.delete-file').click(function() {
                const fileId = $(this).data('id');
                const fileName = $(this).data('name');
                deleteFile(fileId, fileName);
            });
        }
        
        // 渲染分页
        function renderPagination(total, currentPage, totalPages) {
            const pagination = $('#pagination');
            pagination.empty();
            
            // 更新总数显示
            $('#total-count').text(total);
            
            if (total === 0) {
                return;
            }
            
            // 上一页按钮
            pagination.append(`
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="javascript:void(0)" data-page="${currentPage - 1}" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
            `);
            
            // 页码按钮
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, startPage + 4);
            
            for (let i = startPage; i <= endPage; i++) {
                pagination.append(`
                    <li class="page-item ${i === currentPage ? 'active' : ''}">
                        <a class="page-link" href="javascript:void(0)" data-page="${i}">${i}</a>
                    </li>
                `);
            }
            
            // 下一页按钮
            pagination.append(`
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="javascript:void(0)" data-page="${currentPage + 1}" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            `);
            
            // 绑定页码点击事件
            $('.page-link').click(function() {
                if (!$(this).parent().hasClass('disabled') && !$(this).parent().hasClass('active')) {
                    currentPage = parseInt($(this).data('page'));
                    loadFiles();
                }
            });
        }
        
        // 预览文件
        function previewFile(fileId, fileUrl, fileName, fileType) {
            // 设置下载链接
            $('#download-btn').attr('href', `/admin/api/files/${fileId}/download`);
            
            // 设置模态框标题
            $('#preview-modal-label').text(fileName);
            
            // 显示文件信息
            $('#preview-file-info').text(`类型: ${fileType.toUpperCase()}`);
            
            // 清空预览内容
            $('#modal-preview-content').empty();
            
            // 根据文件类型显示预览
            if (isImageFile(fileType)) {
                // 图片预览
                $('#modal-preview-content').html(`<img src="${fileUrl}" class="img-fluid file-preview" alt="${fileName}">`);
            } else if (fileType === 'pdf') {
                // PDF预览
                $('#modal-preview-content').html(`<iframe src="${fileUrl}" width="100%" height="500" frameborder="0"></iframe>`);
            } else {
                // 其他文件类型
                const iconClass = getFileIconClass(fileType);
                $('#modal-preview-content').html(`
                    <div class="text-center mb-3">
                        <i class="bi ${iconClass}" style="font-size: 5rem;"></i>
                    </div>
                    <div>该文件类型无法预览，请下载后查看</div>
                `);
            }
            
            // 显示模态框
            previewModal.show();
        }
        
        // 删除文件
        function deleteFile(fileId, fileName) {
            if (confirm(`确定要删除文件 "${fileName}" 吗？此操作不可恢复。`)) {
                $.ajax({
                    url: `/admin/api/files/${fileId}`,
                    type: 'DELETE',
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('token')
                    },
                    success: function(response) {
                        alert('文件删除成功!');
                        loadFiles(); // 重新加载文件列表
                    },
                    error: function(error) {
                        console.error('文件删除失败', error);
                        alert('文件删除失败: ' + (error.responseJSON?.detail || '服务器错误'));
                    }
                });
            }
        }
        
        // 辅助函数：获取文件扩展名
        function getFileExtension(filename) {
            return filename.split('.').pop().toLowerCase();
        }
        
        // 辅助函数：检查是否为图片文件
        function isImageFile(ext) {
            const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
            return imageExtensions.includes(ext.toLowerCase());
        }
        
        // 辅助函数：获取文件图标类
        function getFileIconClass(ext) {
            ext = ext.toLowerCase();
            
            // 图片文件
            if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext)) {
                return 'bi-file-earmark-image file-image';
            }
            // 文档文件
            else if (['doc', 'docx', 'txt', 'md', 'rtf'].includes(ext)) {
                return 'bi-file-earmark-text file-document';
            }
            // 压缩文件
            else if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) {
                return 'bi-file-earmark-zip file-archive';
            }
            // 代码文件
            else if (['js', 'css', 'html', 'py', 'java', 'c', 'cpp', 'php'].includes(ext)) {
                return 'bi-file-earmark-code file-code';
            }
            // Excel文件
            else if (['xls', 'xlsx', 'csv'].includes(ext)) {
                return 'bi-file-earmark-excel file-excel';
            }
            // PDF文件
            else if (ext === 'pdf') {
                return 'bi-file-earmark-pdf file-pdf';
            }
            // 其他文件
            else {
                return 'bi-file-earmark file-other';
            }
        }
        
        // 辅助函数：格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
    </script>
</body>
</html> 